
package fileby.model.impl.sources.impl;

import fileby.core.SourceType;
import fileby.core.IDisplayableFileSource;
import fileby.model.impl.filemanagement.IFileHandler;
import fileby.model.impl.sources.IFileSourceProvider;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.filechooser.FileSystemView;

/**
 *
 * @author Jacob
 */
class FolderSource extends AbstractFileSource {

    private File directory;
    private IFileHandler fileHandler;
    private IFileSourceProvider fileSourceProvider;

    public FolderSource(File f, IFileSourceProvider fileSourceProvider,
            IFileHandler fileHandler) {
        this.fileSourceProvider = fileSourceProvider;
        this.fileHandler = fileHandler;
        directory = f;
        sourceType = SourceType.FOLDER;
        updateContent();
        writePermission = true;
        changePermission = true;
        name = f.getName();
        if (f.getParent() == null) {
            name = f.getAbsolutePath(); // If it's a device :D
        }
        icon = FileSystemView.getFileSystemView().getSystemIcon(f);
    }

    public void updateContent() {
        List<File> updatedFileList = new ArrayList();
        for(File f : directory.listFiles(getFileFilter()))
            updatedFileList.add(f);

        syncList(updatedFileList);
        sortList();
    }


    public String getAbsolutePath() {
        return directory.getAbsolutePath();
    }

    @Override
    public String toString() {
        return sourceType.toString() + ";" + getAbsolutePath();
    }

    public IDisplayableFileSource getParent() {
        if (directory.getParent() != null)
            return fileSourceProvider.create(SourceType.FOLDER, 
                    new File(directory.getParent()).getAbsolutePath());
        else
            return fileSourceProvider.create(SourceType.COMPUTER);
    }

    public boolean addFiles(List<File> fileList, int action) throws IOException {
        if(fileHandler.addFiles(fileList, directory, action)) {
            updateContent();
            return true;
        }
        return false;
    }

    private FileFilter getFileFilter(){
        return new java.io.FileFilter(){
            public boolean accept(File file){
                return !file.isHidden() && file.canRead()
                        && file.canExecute();
            }};
    }

}
